/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.fresco.animation.drawable.animator;

import com.facebook.fresco.animation.backend.AnimationInformation;
import com.facebook.fresco.animation.drawable.AnimatedDrawable2;
import com.facebook.imagepipeline.annotation.Nullable;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;

/** Helper class to create {@link ohos.agp.animation.AnimatorValue}s for {@link AnimatedDrawable2}. */
public class AnimatedDrawable2ValueAnimatorHelper {
  public static @Nullable AnimatorValue createValueAnimator(
      AnimatedDrawable2 animatedDrawable, int maxDurationMs) {
    AnimatorValue animator = createValueAnimator(animatedDrawable);
    if (animator == null) {
      return null;
    }
    int repeatCount = (int) Math.max(maxDurationMs / animatedDrawable.getLoopDurationMs(), 1);
    animator.setLoopedCount(repeatCount);
    return animator;
  }

  public static AnimatorValue createValueAnimator(AnimatedDrawable2 animatedDrawable) {
    int loopCount = animatedDrawable.getLoopCount();
    AnimatorValue animator = new AnimatorValue();
  //  animator.setIntValues(0, (int) animatedDrawable.getLoopDurationMs());
  //  animator.setDuration(animatedDrawable.getLoopDurationMs());
    animator.setLoopedCount(loopCount != AnimationInformation.LOOP_COUNT_INFINITE ? loopCount : Animator.INFINITE);
    //animator.setRepeatMode(ValueAnimator.RESTART);
    // Use a linear interpolator
    animator.setCurveType(Animator.CurveType.LINEAR);
    AnimatorValue.ValueUpdateListener animatorUpdateListener =
        createAnimatorUpdateListener(animatedDrawable);
    animator.setValueUpdateListener(animatorUpdateListener);
    return animator;
  }

  public static AnimatorValue.ValueUpdateListener createAnimatorUpdateListener(
      final AnimatedDrawable2 drawable) {
    return new AnimatorValue.ValueUpdateListener() {
      @Override
      public void onUpdate(AnimatorValue animatorValue, float v) {
        if(drawable != null){
          drawable.setLevel((int)(v*100));
        }
          //drawable.setLevel((Integer) animation.getAnimatedValue());
      }
    };
  }

  private AnimatedDrawable2ValueAnimatorHelper() {}
}
